package com.alander.nexusgo.user.controller;

import com.alander.nexusgo.common.model.dto.LoginDTO;
import com.alander.nexusgo.common.model.dto.RegisterDTO;
import com.alander.nexusgo.common.response.Result;
import com.alander.nexusgo.framework.web.starter.controller.BaseController;
import com.alander.nexusgo.user.service.UserService;
import com.alander.nexusgo.user.utils.IpUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证权限管理
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController extends BaseController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param loginDTO 登录参数 {username, password}
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginDTO loginDTO,
                                             HttpServletRequest request) {
        try {
            String clientIp = IpUtil.getClientIpv4(request);

            // 执行登录逻辑
            String token = userService.login(loginDTO.getUsername(), loginDTO.getPassword(), clientIp);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);

            return success(result);
        } catch (Exception e) {
            return fail(500, e.getMessage());
        }
    }

    /**
     * 用户注册
     *
     * @param registerDTO 注册参数 {username, password}
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<Boolean> register(@Valid @RequestBody RegisterDTO registerDTO) {
        if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
            return fail("密码不一致");
        }
        try {
            // 执行注册逻辑
            boolean register = userService.register(registerDTO);
            return success(register);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    /**
     * 用户登出
     *
     * @return 登出结果
     */
    @PostMapping("/logout")
    public Result<Boolean> logout() {
        boolean logout = userService.logout();
        return success(logout);
    }

    /**
     * 刷新token
     *
     * @return 新token
     */
    @PostMapping("/refresh")
    public Result<Map<String, String>> refreshToken() {
        String token = userService.refreshToken();
        // 构建返回结果
        Map<String, String> result = new HashMap<>();
        result.put("token", token);
        return success(result);
    }
}
